package vcp.server.requesthandler;

import java.io.IOException;
import java.io.Serializable;

import ocsf.server.ConnectionToClient;
import vcp.client.request.Request;
import vcp.client.request.response.ResponseRefresh;
import vcp.client.request.response.ResponseRequest;
import vcp.server.factories.DAOFactoryAbstract;
import vcp.server.interfaces.IServer;
import vcp.server.utility.Constants;

/**
 * 
 * @author VCP team
 *         <p>
 *         generic class for handling requests from client
 *         </p>
 * @param <T>
 *            instance of class which extends Request
 * 
 */
public abstract class RequestHandler<T extends Request>
{
	protected final IServer server;

	/**
	 * class constructor
	 * 
	 * @param server
	 *            initialized
	 */
	protected RequestHandler(IServer server)
	{
		this.server = server;
	}

	/**
	 * 
	 * @param request
	 *            as request from client
	 * @param client
	 *            thats send the request
	 */
	public abstract void execute(T request, ConnectionToClient client);

	protected DAOFactoryAbstract getDaoFactory()
	{
		return this.server.getDaoFactory();
	}

	/**
	 * 
	 * @param response
	 *            as the answer from server
	 * @param client
	 *            that gets the answer
	 */
	protected void sendResponse(ResponseRequest response, ConnectionToClient client)
	{
		try
		{
			client.sendToClient(response);
		} catch (IOException e)
		{
			System.out.println(client.getInfo(Constants.IP_ADDRESS) + " caused I/O crush");
		}
	}

	/**
	 * method that makes sure all relevant clients gets updated once change was
	 * performed
	 * 
	 * @param data
	 *            that was changed
	 * @param currentClient
	 *            that comitted the change
	 */
	protected void sendResponseRefresh(Serializable data, ConnectionToClient currentClient)
	{
		ResponseRefresh referesh = new ResponseRefresh(data);
		for (ConnectionToClient connection : this.server.getConnections())
		{
			try
			{
				if (!connection.equals(currentClient))
				{
					connection.sendToClient(referesh);
				}
			} catch (IOException e)
			{
				System.out.println(connection.getInfo(Constants.IP_ADDRESS) + " caused I/O crush");
			}
		}
	}
}
